package com.zidian.teacher.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zidian.teacher.R;
import com.zidian.teacher.adapter.StudyGroupAdapter;
import com.zidian.teacher.adapter.StudySelectAdapter;
import com.zidian.teacher.bean.GroupBean;
import com.zidian.teacher.bean.GroupListBean;
import com.zidian.teacher.bean.StudyBean;
import com.zidian.teacher.common.Constant;
import com.zidian.teacher.utils.GetUserInfo;
import com.zidian.teacher.utils.ToastUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

import com.zidian.teacher.bean.PutStudyBean;
import com.zidian.teacher.common.ToolBarActivity;

/**
 * Created by Administrator on 2016/9/6 0006.
 */
public class TeachingWorkStudySelectActivity extends ToolBarActivity {

    @Bind(R.id.group_recycler)
    RecyclerView groupRecycler;
    @Bind(R.id.study_recycler)
    RecyclerView studyRecycler;
    private TextView confirmBtn;

    private StudyGroupAdapter groupAdapter;
    private StudySelectAdapter studyAdapter;
    private LinearLayoutManager mGroupLayoutManager;
    private LinearLayoutManager mStudyLayoutManager;

    private int oldSelectedPosition = 0;
    private String courseId = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolbarView(R.layout.toolbar_both);
        setContentView(R.layout.activity_teaching_work_study_select);
        ButterKnife.bind(this);
        confirmBtn = (TextView) findViewById(R.id.toolbar_sure);
        confirmBtn.setText("保存");
        setTitle("选择学生");
        courseId = getIntent().getStringExtra("courseId");

//        initData();
        getGroupMessage();
        initView();

    }

    private void initView() {

        groupAdapter = new StudyGroupAdapter(this, groupBeanList);
        studyAdapter = new StudySelectAdapter(this, groupBeanList);

        mGroupLayoutManager = new LinearLayoutManager(this);
        mStudyLayoutManager = new LinearLayoutManager(this);

        groupRecycler.setLayoutManager(mGroupLayoutManager);
        studyRecycler.setLayoutManager(mStudyLayoutManager);

        groupRecycler.setAdapter(groupAdapter);
        studyRecycler.setAdapter(studyAdapter);

        //点击分组
        groupAdapter.setOnItemClickListener(new StudyGroupAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                if (groupBeanList.get(position).isSelect()) {
                    changeSelectAll(position);
                } else {
                    changeSelected(position);
                }


            }

            @Override
            public void onItemLongClick(View view, int position) {


            }
        });

        //点击学生
        studyAdapter.setOnItemClickListener(new StudySelectAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                int index = studyAdapter.getStudyListIndex();
                boolean studyAll = true;
                boolean isAll = groupBeanList.get(index).getStudyBeans().get(position).isSelect();
                groupBeanList.get(index).getStudyBeans().get(position).setIsSelect(!isAll);
                for (int i = 0; i < groupBeanList.get(index).getStudyBeans().size(); i++) {
                    if (!groupBeanList.get(index).getStudyBeans().get(i).isSelect()) {
                        studyAll = false;
                    }
                }
                groupBeanList.get(index).setIsAllSelect(!studyAll);
                changeStudySelectAll(index);

            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });

        confirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PutStudyBean confrimBean = getConfrimList();
                Intent intent = new Intent();
                intent.putExtra("study", confrimBean);
                setResult(1002, intent);
                finish();
            }
        });


    }

    private PutStudyBean getConfrimList() {
        PutStudyBean studyBean = new PutStudyBean();
        List<StudyBean> confrimList = new ArrayList<>();
        for (int i = 0; i < groupBeanList.get(0).getStudyBeans().size(); i++) {
            if (groupBeanList.get(0).getStudyBeans().get(i).isSelect()) {
                confrimList.add(groupBeanList.get(0).getStudyBeans().get(i));
            }

        }
        studyBean.setStudyBeans(confrimList);
        return studyBean;
    }

    private void changeSelectAll(int position) {
        boolean isAll = groupBeanList.get(position).isAllSelect();
        if (position == 0) {
            for (int i = 0; i < groupBeanList.size(); i++) {
                groupBeanList.get(i).setIsAllSelect(!isAll);
                groupBeanList.get(i).setAllSelect(!isAll);
            }
        } else {


            if (isAll && groupBeanList.get(0).isAllSelect()) {
                groupBeanList.get(0).setIsAllSelect(!isAll);
            }
            groupBeanList.get(position).setIsAllSelect(!isAll);
            groupBeanList.get(position).setAllSelect(!isAll);
            if (groupBeanList.get(0).getAllSelect()) {
                groupBeanList.get(0).setIsAllSelect(!isAll);
            }


        }
        studyAdapter.setGroupList(groupBeanList);
        groupAdapter.notifyDataSetChanged();
        studyAdapter.notifyDataSetChanged();
    }

    private void changeStudySelectAll(int position) {
        boolean isAll = groupBeanList.get(position).isAllSelect();
        if (position == 0) {
            boolean isGroup = true;
            for (int j = 0; j < groupBeanList.size(); j++) {
                boolean is = true;
                for (int i = 0; i < groupBeanList.get(j).getStudyBeans().size(); i++) {
                    if (!groupBeanList.get(j).getStudyBeans().get(i).isSelect()) {
                        is = false;
                        isGroup = false;
                    }
                }
                groupBeanList.get(j).setIsAllSelect(is);
            }
            groupBeanList.get(position).setIsAllSelect(isGroup);
        } else {


            if (isAll && groupBeanList.get(0).isAllSelect()) {
                groupBeanList.get(0).setIsAllSelect(!isAll);
            }
            groupBeanList.get(position).setIsAllSelect(!isAll);
            if (groupBeanList.get(0).getAllSelect()) {
                groupBeanList.get(0).setIsAllSelect(!isAll);
            }
        }

        studyAdapter.setGroupList(groupBeanList);
        groupAdapter.notifyDataSetChanged();
        studyAdapter.notifyDataSetChanged();
    }

    private void changeSelected(int position) {
        groupBeanList.get(oldSelectedPosition).setIsSelect(false);
        groupBeanList.get(position).setIsSelect(true);
        //增加左侧联动
//        groupRecycler.scrollToPosition(position);
        oldSelectedPosition = position;
        studyAdapter.setGroupList(groupBeanList);
        groupAdapter.notifyDataSetChanged();
        studyAdapter.notifyDataSetChanged();
    }


    private List<GroupBean> groupBeanList = new ArrayList<>();

    private void initData(GroupListBean model) {

        List<StudyBean> all = new ArrayList<>();

        for (int i = 0; i < model.getData().size(); i++) {
            List<StudyBean> group = new ArrayList<>();
            if (model.getData().get(i).getGroup() != null ){
                if (model.getData().get(i).getGroup().size() == 0) {
                    continue;
                }
                for (int j = 0; j < model.getData().get(i).getGroup().size(); j++) {
                    group.add(new StudyBean(model.getData().get(i).getGroup().get(j).getStudentHeadPortrait(),
                            model.getData().get(i).getGroup().get(j).getStudentName(),
                            model.getData().get(i).getGroup().get(j).getStudentId(),
                            model.getData().get(i).getGroup().get(j).getGroupId(), false));
                }
            }

            all.addAll(group);
            GroupBean g = new GroupBean(model.getData().get(i).getGroupingName(), group.size() + "",
                    model.getData().get(i).getGroupingId(), false, false, group);
            groupBeanList.add(g);
        }
        GroupBean allG = new GroupBean("全部", all.size() + "", "0", false, true, all);
        groupBeanList.add(0, allG);
        studyAdapter.setGroupList(groupBeanList);
        groupAdapter.notifyDataSetChanged();
        studyAdapter.notifyDataSetChanged();


    }

    private void getGroupMessage() {

        String loginUrl = Constant.URL_GOAL + "work/student";
        HashMap<String, String> map = new HashMap<>();
        map.put("courseId", courseId);
        map.put("teacherId", GetUserInfo.getTeacherId(context));
        map.put("className", "");
        map.put("token", GetUserInfo.getToken(context));


        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

                ToastUtil.showToast(context, "获取列表失败！");
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e("T", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        ToastUtil.showToast(context, jsonObject.getString("message"));
                        return;
                    } else {
//                        ToastUtil.showToast(context, "成功！");
                    }

                } catch (JSONException e) {

                }

                Gson gson = new Gson();
                GroupListBean model = gson.fromJson(response, GroupListBean.class);
                if (model.isSuccess()) {
                    initData(model);
                }

            }
        });
    }

}
